package com.zhangxuehai.android.pdfviewer.annotation;

import com.zhangxuehai.android.pdfviewer.annotation.pen.PenBuilder;
import com.zhangxuehai.android.pdfviewer.annotation.pen.PenType;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;

/**
 * @author 章学海
 * @date 2020/1/9
 */
public class AnnotationBean {
    @SerializedName("PenType")
    public PenType penType;
    @SerializedName("Data")
    public String data;
    @SerializedName("PageIndex")
    public int pageIndex;
    @SerializedName("Id")
    public String id;

    public AnnotationBean(PenType penType, String data, int pageIndex, String id) {
        this.penType = penType;
        this.data = data;
        this.pageIndex = pageIndex;
        this.id = id;
    }

    public AnnotationBean(BaseAnnotation baseAnnotation) {
        penType = baseAnnotation.pen.getPenType();
        Gson gson = new Gson();
        JsonObject jsonObject = gson.toJsonTree(baseAnnotation).getAsJsonObject();
        String penString =jsonObject.get("pen").toString();
        jsonObject.remove("pen");
        jsonObject.addProperty("pen",penString);
        id = jsonObject.get("id").getAsString();
        pageIndex = jsonObject.get("page").getAsInt();
        data =  jsonObject.toString();
    }
    public BaseAnnotation getAnnotation() throws Exception{
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(data,JsonObject.class);
        String penString = jsonObject.get("pen").getAsString();
        jsonObject.remove("pen");
        BaseAnnotation annotation = null;
        switch (penType){
            case COLOR:
            case BRUSH:
                annotation = gson.fromJson(jsonObject,PenAnnotation.class);
                break;
            case SELECTED:
            case STRIKETHROUGH:
            case UNDERLINE:
                annotation = gson.fromJson(jsonObject,MarkAnnotation.class);
                break;
            default: throw new RuntimeException("错误的注释类型");
        }
        annotation.pen = PenBuilder.getPen(penType,penString,gson);
        return annotation;
    }
}
